package cn.tanghom.support.utils;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import cn.tanghom.conf.CommonKey;

/**
 * 云片短信发送
 *
 * @author tanghom<tanghom@qq.com> on 2016/6/23
 */
public class YunPianSms {
    //查账户信息的http地址
    private static String URI_GET_USER_INFO = "https://sms.yunpian.com/v1/user/get.json";

    //智能匹配模板发送接口的http地址
    private static String URI_SEND_SMS = "https://sms.yunpian.com/v1/sms/send.json";

    //apikey
    private static String APP_KEY = CommonKey.application.getProperty("YunPianAppKey","375914b1295f3bf7ceb4e0a2778adddf");


    /**
     * 取账户信息
     *
     * @return json格式字符串
     */

    public static String getUserInfo() {
        Map<String, String> params = new HashMap<String, String>();
        params.put("apikey", APP_KEY);
        return HttpClientUtils.post(URI_GET_USER_INFO, params);
    }

    /**
     * 智能匹配模板接口发短信
     *
     * @param text   　短信内容
     * @param mobile 　接受的手机号
     * @return json格式字符串
     */

    public static String sendSms(String text, String mobile) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("apikey", APP_KEY);
        params.put("text", "程序运行异常，异常代码" + text);
        params.put("mobile", mobile);
        return HttpClientUtils.post(URI_SEND_SMS, params);
    }

    public static String sendCode(String mobile) {
        Random random = new Random();
        String code = random.nextInt(9000) + 1000 + "";
        String text = "【云片网】您的验证码是" + code;
        Map<String, String> params = new HashMap<String, String>();
        params.put("apikey", APP_KEY);
        params.put("text", text);
        params.put("mobile", mobile);
        Map<String, Object> retu = JsonUtil.toObject(HttpClientUtils.post(URI_SEND_SMS, params), Map.class);
        double codes = (double) retu.get("code");
        int returnCode = (int) codes;
        if (0 != returnCode) {
            throw new RuntimeException(retu.get("msg").toString());
        }
        return code;
    }
    
    public static String sendCode(String mobile,String code) {      
        String text = "【云片网】您的验证码是" + code;
        Map<String, String> params = new HashMap<String, String>();
        params.put("apikey", APP_KEY);
        params.put("text", text);
        params.put("mobile", mobile);
        Map<String, Object> retu = JsonUtil.toObject(HttpClientUtils.post(URI_SEND_SMS, params), Map.class);
        double codes = (double) retu.get("code");
        int returnCode = (int) codes;
        if (0 != returnCode) {
            throw new RuntimeException(retu.get("msg").toString());
        }
        return code;
    }

    public static void main(String[] args) throws IOException, URISyntaxException {

        System.out.println(YunPianSms.sendSms("xa", "18613236735"));
    }
}
